package recursion

import problem.Problem

class Q50Pow extends Problem {

  def myPow(x: Double, n: Int): Double = {
    if (n < 0) 1 / pow(x, -n.toLong) else pow(x, n.toLong)
  }

  def pow(x: Double, n: Long): Double = {
    if (n == 0) 1
    else if (n == 1) x
    else {
      val h = n / 2
      val hv = pow(x, h)
      if (n % 2 == 1) hv * hv * x else hv * hv
    }
  }

  override def test(): Unit = {
    myPow(2.0, 10) shouldBe 1024.0 +- 1e-5
    myPow(2.0, 2) shouldBe 4.0 +- 1e-5
    myPow(2.1, 3) shouldBe 9.261 +- 1e-5
    myPow(2.0, -2) shouldBe 0.25 +- 1e-5
    myPow(2.00000, -2147483648) shouldBe 0.0 +- 1e-5
  }
}
